import os
from werkzeug.utils import secure_filename
from uuid import uuid4
from flask import current_app

def save_file(file, folder):
    """
    保存上传的文件
    :param file: FileStorage对象
    :param folder: 保存的文件夹名
    :return: 文件保存的相对路径
    """
    # 安全的文件名
    filename = secure_filename(file.filename)
    # 使用UUID生成唯一文件名
    unique_filename = f"{uuid4().hex}_{filename}"
    
    # 确保目标文件夹存在
    upload_path = os.path.join('static', current_app.config['UPLOAD_FOLDER'], folder)
 
    os.makedirs(upload_path, exist_ok=True)
    
    # 保存文件
    file_path = os.path.join(upload_path, unique_filename)
    file.save(file_path)
    
    # 返回相对路径 API_URL
    return f"/static/{current_app.config['UPLOAD_FOLDER']}/{folder}/{unique_filename}"